package com.suanfa.sort;

/**
 * 快速排序
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] arr={ 49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22};
        quickSort(arr, 0, arr.length-1);
        for(int i: arr){
            System.out.print(i + ",");
        }
    }



    public static void quickSort(int[] arr, int left, int right){
        if(left < right){
            int middle = partition(arr, left, right);
            quickSort(arr, left, middle -1);
            quickSort(arr, middle + 1, right);
        }
    }



    public static int partition(int[] arr, int left, int right){

        int pivot = arr[left];
        while(left < right){
            //大于基准数右指针往左
             while(arr[right] > pivot && right > left){
                 right --;
             }
             //有匹配项，需调换
             if(right > left){
                 arr[left] = arr[right];
                 left ++;
             }
            //小于基准数左指针往右
            while(arr[left] < pivot && left < right){
                left ++;
            }
            if(left < right){
                arr[right] = arr[left];
                right --;
            }
        }
        //将基准元素置于中间元素
        arr[left] = pivot;
        return left;
    }

}
